<script setup lang="ts">
import { ref, onMounted, onUnmounted, reactive, watch, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { Terminal } from 'xterm'
import { FitAddon } from 'xterm-addon-fit'
import { saveAs } from 'file-saver'
import 'xterm/css/xterm.css'
import LokiLogService from './loki-log-service'
import type { LogQueryParams, LokiLogViewerProps, NamespacePodPair } from './types'

// 定义组件属性
const props = withDefaults(defineProps<LokiLogViewerProps>(), {
  title: 'Loki日志查询工具',
  height: '100%',
  width: '100%',
  autoRefreshInterval: 5000,
  defaultTimeRange: 60,
  showDownloadButton: true,
  showLiveModeButton: true,
  showClearButton: true,
  terminalOptions: () => ({}),
  customClass: ''
  // namespace和pod现在是必需参数，不再提供默认值
})

// 定义组件事件
const emit = defineEmits<{
  'logs-loaded': [logs: string[]]
  'error': [error: any]
  'live-mode-change': [isLive: boolean]
}>()

// 创建Loki服务实例
const lokiService = new LokiLogService(props.lokiApiBaseUrl)

// 初始化xterm终端
let terminal: Terminal | null = null
let fitAddon: FitAddon | null = null

// 日志查询相关状态

// 时间范围选择
const timeRange = ref<[Date, Date] | null>(null)

// 关键词搜索
const keyword = ref('')

// 当前选中的namespace/pod组合索引
const currentPairIndex = ref(0)

// 所有可用的namespace/pod组合
const namespacePodPairs = ref<NamespacePodPair[]>([])

// 日志查询参数
const queryParams = reactive<LogQueryParams>({
  namespace: '',
  pod: '',
  startTime: '',
  endTime: '',
  keyword: ''
})

// 控制状态
const isLoading = ref(false)
const isLiveMode = ref(false)
const liveInterval = ref<number | null>(null)

// 调整终端大小的处理函数
const handleResize = () => {
  fitAddon?.fit()
}

// 初始化终端
const initTerminal = () => {
  const terminalElement = document.getElementById('terminal')
  if (!terminalElement) return
  
  // 创建FitAddon实例
  fitAddon = new FitAddon()
  
  // 合并默认终端选项和用户提供的选项
  const terminalConfig = {
    cursorBlink: false,
    disableStdin: true,
    fontSize: props.terminalOptions?.fontSize || 12,
    lineHeight: props.terminalOptions?.lineHeight || 1.2,
    scrollback: props.terminalOptions?.scrollback || 5000,
    theme: {
      background: props.terminalOptions?.theme?.background || '#1e1e1e',
      foreground: props.terminalOptions?.theme?.foreground || '#f8f8f8'
    },
    cols: props.terminalOptions?.cols || 120,
    rows: props.terminalOptions?.rows || 30,
    rendererType: 'canvas',
    convertEol: true
  }
  
  terminal = new Terminal(terminalConfig)
  
  // 加载FitAddon
  terminal.loadAddon(fitAddon)
  
  terminal.open(terminalElement)
  // 调整终端大小以适应容器
  setTimeout(() => {
    fitAddon?.fit()
  }, 100)
  
  terminal.writeln('欢迎使用Loki日志查询工具...')
  terminal.writeln('请选择命名空间和Pod，然后点击查询按钮获取日志。')
  
  // 监听窗口大小变化，调整终端大小
  window.addEventListener('resize', handleResize)
}



// 查询日志
const queryLogs = async () => {
  if (!terminal) return
  
  // 检查时间范围
  if (!timeRange.value && !isLiveMode.value) {
    ElMessage.warning('请选择时间范围或启用实时模式')
    return
  }
  
  if (!timeRange.value && !isLiveMode.value) {
    ElMessage.warning('请选择时间范围或启用实时模式')
    return
  }
  
  try {
    isLoading.value = true
    terminal?.clear()
    terminal?.writeln('正在查询日志...')
    
    // 更新查询参数
    // 使用当前选中的namespace/pod组合
    updateQueryParamsFromCurrentPair()
    
    queryParams.keyword = keyword.value
    
    if (!isLiveMode.value && timeRange.value) {
      queryParams.startTime = timeRange.value[0].toISOString()
      queryParams.endTime = timeRange.value[1].toISOString()
    } else {
      // 实时模式使用当前时间前5分钟作为开始时间
      const now = new Date()
      const fiveMinutesAgo = new Date(now.getTime() - 5 * 60 * 1000)
      queryParams.startTime = fiveMinutesAgo.toISOString()
      queryParams.endTime = now.toISOString()
    }
    
    const logs = await lokiService.queryLogs(queryParams)
    
    if (logs.length === 0) {
      terminal?.writeln('未找到匹配的日志记录')
    } else {
      logs.forEach(log => {
        terminal?.writeln(log)
      })
      terminal?.writeln(`共找到 ${logs.length} 条日志记录`)
    }
    
    // 触发日志加载完成事件
    emit('logs-loaded', logs)
  } catch (error) {
    ElMessage.error('查询日志失败')
    console.error(error)
    terminal?.writeln('查询日志失败，请检查查询参数或网络连接')
    emit('error', error)
  } finally {
    isLoading.value = false
  }
}

// 切换实时日志模式
const toggleLiveMode = () => {
  isLiveMode.value = !isLiveMode.value
  
  // 触发实时模式变更事件
  emit('live-mode-change', isLiveMode.value)
  
  if (isLiveMode.value) {
    // 启动实时日志查询
    if (liveInterval.value) {
      clearInterval(liveInterval.value)
    }
    
    // 立即执行一次查询
    queryLogs()
    
    // 设置定时器，使用配置的刷新间隔
    liveInterval.value = setInterval(() => {
      queryLogs()
    }, props.autoRefreshInterval) as unknown as number
    
    ElMessage.success('已启动实时日志查询')
  } else {
    // 停止实时日志查询
    if (liveInterval.value) {
      clearInterval(liveInterval.value)
      liveInterval.value = null
    }
    ElMessage.info('已停止实时日志查询')
  }
}

// 下载日志
const downloadLogs = () => {
  if (!terminal) return
  
  const logContent = terminal.buffer.active.getLine(0)?.translateToString() || ''
  if (!logContent.trim()) {
    ElMessage.warning('没有可下载的日志内容')
    return
  }
  
  // 收集所有行的内容
  let allLogs = ''
  for (let i = 0; i < terminal.buffer.active.length; i++) {
    const line = terminal.buffer.active.getLine(i)
    if (line) {
      allLogs += line.translateToString() + '\n'
    }
  }
  
  // 创建Blob并下载
  const blob = new Blob([allLogs], { type: 'text/plain;charset=utf-8' })
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
  const filename = `loki-logs-${queryParams.namespace}-${queryParams.pod}-${timestamp}.txt`
  saveAs(blob, filename)
  
  ElMessage.success('日志已下载')
}

// 清空终端
const clearTerminal = () => {
  if (terminal) {
    terminal.clear()
    terminal?.writeln('终端已清空')
  }
}

// 监听外部传入的namespace和pod变化
watch(() => props.namespace, (newVal) => {
  if (newVal && props.pod) {
    // 如果没有namespacePodPairs或只有一个与当前不同的组合，则重新初始化
    if (namespacePodPairs.value.length === 0 ||
        (namespacePodPairs.value.length === 1 && 
         (namespacePodPairs.value[0].namespace !== newVal || namespacePodPairs.value[0].pod !== props.pod))) {
      initNamespacePodPairs()
    }
  }
})

watch(() => props.pod, (newVal) => {
  if (newVal && props.namespace) {
    // 如果没有namespacePodPairs或只有一个与当前不同的组合，则重新初始化
    if (namespacePodPairs.value.length === 0 ||
        (namespacePodPairs.value.length === 1 && 
         (namespacePodPairs.value[0].namespace !== props.namespace || namespacePodPairs.value[0].pod !== newVal))) {
      initNamespacePodPairs()
    }
  }
})

// 监听外部传入的namespacePodPairs变化
watch(() => props.namespacePodPairs, (newVal) => {
  if (newVal && newVal.length > 0) {
    initNamespacePodPairs()
  }
}, { deep: true })

// 初始化namespace/pod组合列表
const initNamespacePodPairs = () => {
  // 清空现有列表
  namespacePodPairs.value = []
  
  // 如果提供了namespacePodPairs属性，则使用它
  if (props.namespacePodPairs && props.namespacePodPairs.length > 0) {
    namespacePodPairs.value = [...props.namespacePodPairs]
  }
  // 如果提供了单个namespace和pod，则添加到列表中（向后兼容）
  else if (props.namespace && props.pod) {
    namespacePodPairs.value.push({
      namespace: props.namespace,
      pod: props.pod,
      displayName: `${props.namespace}/${props.pod}`
    })
  }
  
  // 如果列表不为空，则更新查询参数
  if (namespacePodPairs.value.length > 0) {
    updateQueryParamsFromCurrentPair()
  }
}

// 根据当前选中的namespace/pod组合更新查询参数
const updateQueryParamsFromCurrentPair = () => {
  if (namespacePodPairs.value.length > 0 && currentPairIndex.value < namespacePodPairs.value.length) {
    const currentPair = namespacePodPairs.value[currentPairIndex.value]
    queryParams.namespace = currentPair.namespace
    queryParams.pod = currentPair.pod
  }
}

// 切换当前选中的namespace/pod组合
const switchNamespacePodPair = (index: number) => {
  if (index >= 0 && index < namespacePodPairs.value.length) {
    currentPairIndex.value = index
    updateQueryParamsFromCurrentPair()
    
    // 如果处于实时模式，则重新查询日志
    if (isLiveMode.value) {
      queryLogs()
    }
  }
}

// 组件挂载时初始化
onMounted(() => {
  initTerminal()
  
  // 初始化namespace/pod组合列表
  initNamespacePodPairs()
  
  // 设置默认时间范围
  const now = new Date()
  const defaultStartTime = new Date(now.getTime() - props.defaultTimeRange * 60 * 1000)
  timeRange.value = [defaultStartTime, now]
})

// 组件卸载时清理资源
onUnmounted(() => {
  if (liveInterval.value) {
    clearInterval(liveInterval.value)
  }
  // 移除窗口大小变化监听器
  window.removeEventListener('resize', handleResize)
  terminal?.dispose()
})

// 暴露组件方法供父组件调用
defineExpose({
  queryLogs,
  clearTerminal,
  toggleLiveMode,
  downloadLogs,
  switchNamespacePodPair
})
</script>

<template>
  <div class="loki-log-viewer" :class="customClass" :style="{ width, height }">
    <el-card class="dashboard-card">
      <template #header>
        <div class="card-header">
          <h2>{{ title }}</h2>
        </div>
      </template>
      
      <div class="filter-section">
        <el-row :gutter="20">
          <!-- 显示当前选择的namespace和pod -->
          <el-col :span="8">
            <el-select 
              v-model="currentPairIndex" 
              placeholder="选择命名空间/Pod" 
              class="full-width"
              @change="switchNamespacePodPair"
            >
              <el-option 
                v-for="(pair, index) in namespacePodPairs" 
                :key="index" 
                :label="pair.displayName || `${pair.namespace}/${pair.pod}`" 
                :value="index" 
              />
            </el-select>
          </el-col>
          
          <!-- 时间范围选择器 -->
          <el-col :span="8">
            <el-date-picker
              v-model="timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :disabled="isLiveMode"
              class="full-width"
            />
          </el-col>
          
          <!-- 关键词搜索 -->
          <el-col :span="8">
            <el-input
              v-model="keyword"
              placeholder="输入关键词搜索"
              clearable
              class="full-width"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" class="mt-20">
          <el-col :span="24" class="action-buttons">
            <el-button type="primary" @click="queryLogs" :loading="isLoading">
              <el-icon><Search /></el-icon> 查询日志
            </el-button>
            
            <el-button 
              v-if="showLiveModeButton"
              :type="isLiveMode ? 'danger' : 'success'"
              @click="toggleLiveMode"
              :loading="isLoading"
            >
              <el-icon v-if="isLiveMode"><VideoPlay /></el-icon>
              <el-icon v-else><VideoPause /></el-icon>
              {{ isLiveMode ? '停止实时日志' : '开始实时日志' }}
            </el-button>
            
            <el-button 
              v-if="showClearButton"
              type="info" 
              @click="clearTerminal"
            >
              <el-icon><Delete /></el-icon> 清空终端
            </el-button>
            
            <el-button 
              v-if="showDownloadButton"
              type="warning" 
              @click="downloadLogs"
            >
              <el-icon><Download /></el-icon> 下载日志
            </el-button>
          </el-col>
        </el-row>
      </div>
      
      <div class="terminal-container">
        <div id="terminal"></div>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.loki-log-viewer {
  display: flex;
  flex-direction: column;
}

.dashboard-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-section {
  margin-bottom: 20px;
}

.full-width {
  width: 100%;
}

.mt-20 {
  margin-top: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.terminal-container {
  flex: 1;
  background-color: #1e1e1e;
  border-radius: 4px;
  padding: 10px;
  overflow: hidden;
  min-height: 400px;
  display: flex;
  flex-direction: column;
  width: 100%;
}

#terminal {
  width: 100%;
  height: 100%;
  flex: 1;
}
</style>